<template>
  <a-modal
    v-model="state.visiable"
    v-if="state.visiable"
    width="min(90%,1000px)"
    destroy-on-close
    :after-close="afterClose"
    :dialog-style="{ top: '30px' }"
    @cancel="clickCancel"
  >
    <template #footer>
      <a-button key="back" @click="clickCancel"> 取消 </a-button>
      <a-button
        key="submit"
        type="primary"
        @click="clickOk"
        :loading="state.selectLoading || state.submitLoading"
      >
        确定
      </a-button>
    </template>
    <a-spin :spinning="state.selectLoading || state.submitLoading">
      <!-- 自定义头部标题 -->
      <h2>
        <div class="modal-title">
          <img class="title-icon" src="@/assets/images/notifyTodo.svg" />
          <div class="title-txt">
            <span>通知消息</span>
          </div>
          <div
            class="title-remark"
            v-if="state.allNotifications.length > 1 && businessType !== 2"
          >
            <a-space>
              <a-icon type="info-circle" />
              <span>&nbsp;通知你需要通知的角色，无需通知则不勾选</span>
            </a-space>
          </div>
          <div class="title-remark" v-if="state.allNotifications.length === 1">
            <a-space>
              <a-icon type="info-circle" />
              <span>{{ this.state.allNotifications[0].titleContent }}</span>
            </a-space>
          </div>
        </div>
      </h2>
      <div class="modal-main">
        <div
          class="modal-content"
          :class="{
            bottom: index !== state.allNotifications.length - 1,
            selectedContent: item.isSelected,
            unSelectedContent: !item.isSelected
          }"
          v-for="(item, index) in state.allNotifications"
          :key="index"
        >
          <div
            class="modal-top-left-btn"
            :class="{ selected: item.isSelected }"
            @click="clickNotifications(item)"
          >
            <span>选&nbsp;中</span>
          </div>
          <div class="modal-content-left">
            <div class="modal-notication-text">
              <span>{{ item.leftContent.selectLabel }}</span>
            </div>
            <a-form>
              <div>
                <span class="form-label"> 被通知人 </span>
              </div>
              <a-form-item>
                <!--                @change="(e) => {changeSelectedUser(e,index)}">-->
                <a-select
                  v-model="item.leftContent.selectedUserId"
                  show-search
                  placeholder="请选择"
                  style="width: 15vw"
                  allow-clear
                  @change="
                    e => {
                      changeSelectedUser(index, e)
                    }
                  "
                  :filter-option="searchUser"
                >
                  <a-select-option
                    v-for="u in item.leftContent.notifyUserArr"
                    :key="u.userId"
                    :value="u.userId"
                  >
                    {{ u.fullName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <div><span class="form-label">通知内容</span></div>
              <a-form-item>
                <a-textarea
                  v-model="item.leftContent.msg"
                  :rows="3"
                  style="resize: none !important"
                />
              </a-form-item>
            </a-form>
          </div>
          <div class="modal-content-right">
            <div class="text-center mb10 content-title">
              <span>预&nbsp;&nbsp;览</span>
            </div>
            <div>
              <ul
                id="message-list-cpCard"
                class="list-style-none message-front d-absolute"
              >
                <li
                  class="flex-direction-reverse text-left chat-left d-flex mt10"
                >
                  <!-- 头像 -->
                  <img
                    :title="item.rightContent.username"
                    :name="item.rightContent.username"
                    :src="item.rightContent.headImg || state.defaultHeadImg"
                    alt=""
                  />
                  <div class="flex-one">
                    <!-- 名称 & 时间 -->
                    <p class="chat-name">
                      <span>{{ item.rightContent.username }}</span> &nbsp;
                      <span>{{ item.rightContent.gmtCreate }}</span>
                    </p>
                    <!-- 消息 -->
                    <div>
                      <p
                        v-if="item.leftContent.msg"
                        class="break-word chart-msg-before"
                        style="padding: 6px"
                      >
                        {{ item.leftContent.msg }}
                        <span
                          style="color: blue"
                          v-if="item.rightContent.assignedPersonName"
                          >@{{ item.rightContent.assignedPersonName }}</span
                        >
                      </p>
                    </div>
                    <div style="text-align: left">
                      <span class="d-relative">
                        <img
                          v-for="(url, urlINdex) in item.urls || []"
                          :key="url + urlINdex"
                          v-view-image
                          style="margin-left: 10px"
                          class="chat-img mb4"
                          :src="url"
                          alt=""
                        />
                      </span>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>
<script>
import {
  todo_complete_post,
  todo_get_config_user_post,
  todo_get_page_config_post,
  todo_get_process_post,
  todo_initiation_post
} from 'server/modules/7537'
import { cp_card_query_cp_card_post } from 'server/modules/4494'
import { cloneDeep } from 'lodash'
import initationTodo from '@/components/todoTable/hooks/initationTodo'

export default {
  name: 'CpCard',
  mixins: [initationTodo],
  props: {
    showTodo: {
      type: Boolean,
      default: true
    },
    /*
        bomAdjust 调整BOM
        processAdjust 调整工艺单
        bulkAdjust 调整大货工艺单
      */
    businessModelCode: {
      type: String,
      default: null
    },
    /*
        新增 / 修改
     */
    operationType: {
      type: String,
      default: null
    },
    /*
        调整工艺 / 核价
     */
    businessType: {
      type: String,
      default: null
    },
    params: {
      type: Object,
      default() {
        return {
          cp: null,
          bomVersion: null,
          largeProcessVersion: null,
          supplierId: null,
          supplierName: null,
          blukVerison: null,
          initTime: null
        }
      }
    },
    taskModelType: {
      type: String,
      default: null
    },
    mutiMode: {
      type: Boolean,
      default: false
    },
    pageCode: {
      type: String,
      default: null
    }
  },
  watch: {
    params: {
      handler(val, oldValue) {
        if (val) {
          this.state.params = val
          this.initMethods()
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    // 赋值右侧时间
    // this.state.allNotifications[index].rightContent.massageList[0].gmtCreate = this.formattedDateTime()
  },
  data() {
    return {
      state: {
        submitLoading: false,
        selectLoading: true,
        visiable: false,
        defaultHeadImg: 'https://cdn-image.kapeixi.cn/web/images/headImg.png',
        allNotifications: [],
        params: {},
        cpInfo: {
          fatherCp: null,
          fatherCpId: null
        },
        // 工艺员
        craftsmanId: null,
        craftsmanName: null,
        // 制版师
        platemakerId: null,
        platemakerName: null,
        //设计师
        designerId: null,
        designerName: null,
        notificationObj: {
          businessModelCode: null,
          taskModelType: null,
          pageCode: null,
          userDuty: null,
          businessType: null,
          operationType: null,
          isSelected: false,
          title: null,
          selectLoading: true,
          params: {
            bomVersion: null,
            largeProcessVersion: null,
            supplierId: null,
            supplierName: null
          },
          type: null,
          leftContent: {
            selectLabel: null,
            notifyUserArr: [],
            selectedUserId: null,
            msg: null
          },
          rightContent: {
            msg: null,
            username: window.localStorage.userName,
            headImg: null,
            gmtCreate: null,
            assignedPersonName: null
          },
          disposalUrlJsonStr: null,
          viewUrlJsonStr: null,
          disposeUrlParams: {},
          viewUrlParams: {}
        },
        initationParam: {
          businessModelCode: null,
          operationType: null,
          businessType: null,
          receiver: null,
          cp: this.params.cp,
          bomVersion: null,
          blukVerison: null,
          notificationText: null,
          addressData: null,
          taskAddress: null,
          taskModelType: null
        }
      }
    }
  },
  methods: {
    async sendMsgBoard(paramsArr) {
      for (const elem of paramsArr) {
        const content = elem.notificationText.concat(
          '<span contenteditable=\\"false\\" class=\\"color-1989fa\\">@',
          this.state.allNotifications[0].rightContent.assignedPersonName,
          '</span>'
        )
        const params = {
          cp: this.state.cpInfo.fatherCp,
          contentType: 1,
          content,
          userIds: [elem.receiver],
          cpCardId: this.state.cpInfo.fatherCpId
        }
        await this.sendBoardMsg(params)
      }
    },
    deassignParams(variable, template) {
      if (!variable || !template) {
        this.$message.error('参数模板为空')
        return
      }
      template = JSON.parse(template)
      for (const key1 of Object.keys(variable)) {
        for (const key2 of Object.keys(template)) {
          if (variable[key1] && key1 === key2) {
            template[key2] = variable[key1]
            break
          }
        }
      }
      template.id = this.state.cpInfo.fatherCp

      if (this.params.cp !== this.state.cpInfo.fatherCp) {
        template.cp = this.state.cpInfo.fatherCp
      } else {
        template.cp = this.params.cp
      }
      template.skipCp = this.params.cp
      return JSON.stringify(template)
    },
    clickNotifications(item) {
      if (!this.mutiMode) {
        const temp = item.isSelected
        this.state.allNotifications.forEach(elem => {
          elem.isSelected = false
        })
        item.isSelected = !temp
      } else {
        item.isSelected = !item.isSelected
      }
    },
    afterClose() {
      this.state.allNotifications = []
    },
    async clickOk() {
      this.state.submitLoading = true
      const initaionParams = { reqs: [] }
      for (const elem of this.state.allNotifications) {
        if (elem.isSelected) {
          initaionParams.reqs.push(elem)
        }
      }

      if (initaionParams.reqs.length > 0) {
        const paramsArr = this.trans2RequestParams(initaionParams.reqs)
        if (
          paramsArr.length === 0 ||
          paramsArr.length !== initaionParams.reqs.length
        ) {
          return
        }
        const initiationParam = {
          reqs: paramsArr
        }
        await this.todoInitiation(initiationParam)
        await this.sendMsgBoard(paramsArr)
      }
      this.state.submitLoading = false
      this.$emit('closeTodoModal')
    },
    trans2RequestParams(arr) {
      const res = []
      const requestParam = {}
      for (const elem of arr) {
        requestParam.cp = this.params.cp
        requestParam.businessModelCode = elem.businessModelCode
        requestParam.operationType = elem.operationType
        requestParam.businessType = elem.businessType
        if (elem.leftContent.selectedUserId) {
          requestParam.receiver = elem.leftContent.selectedUserId
        } else {
          this.$message.error(
            ''.concat(elem.leftContent.selectLabel, '未选择被通知人')
          )
          this.state.submitLoading = false
          break
        }
        requestParam.notificationText = elem.leftContent.msg
        requestParam.addressData = elem.disposeUrlParams
        requestParam.taskAddress = elem.viewUrlParams
        requestParam.taskModelType = elem.taskModelType
        if (this.params.bomVersion) {
          requestParam.bomVersion = this.params.bomVersion
        }
        if (this.params.blukVerison) {
          requestParam.blukVerison = this.params.blukVerison
        }
        if (this.params.businessDataCode) {
          requestParam.businessDataCode = this.params.businessDataCode
        }
        if (this.params.businessId) {
          requestParam.businessId = this.params.businessId
        }
        res.push(requestParam)
      }
      return res
    },
    // 完成待办
    async todoComplete(params) {
      const { success, retInfo, data } = await todo_complete_post(params)
      if (success) {
        this.$message.success(data)
      } else {
        console.log(retInfo)
      }
    },
    // 查看关联工艺员等
    async cpCardquery() {
      if (!this.params.cp) {
        return
      }
      const { success, retInfo, data } = await cp_card_query_cp_card_post({
        cp: this.params.cp,
        menuType: 'design'
      })
      if (success) {
        if (data.craftsmanId) {
          this.state.craftsmanId = data.craftsmanId
          this.state.craftsmanName = data.craftsmanName
        }

        if (data.platemakerId) {
          this.state.platemakerId = data.platemakerId
          this.state.platemakerName = data.platemakerName
        }
        if (data.designerId) {
          this.state.designerId = data.designerId
          this.state.designerName = data.designerName
        }
        this.$emit('changeFlag', data.overPriceFlage)
      } else {
        this.$message.error(retInfo)
      }
    },
    // 获取配置默认文本
    async todoGetPageConfig() {
      this.state.allNotifications = []
      const { success, retInfo, data } = await todo_get_page_config_post({
        pageCode: this.businessModelCode
      })
      if (success) {
        if (data) {
          const tempTime = this.formattedDateTime()
          let index = 0
          for (const elem of data) {
            const tempNotification = cloneDeep(this.state.notificationObj)
            tempNotification.businessModelCode = elem.businessModelCode
            tempNotification.pageCode = elem.pageCode
            tempNotification.userDuty = elem.userDuty
            tempNotification.businessType = elem.businessType
            tempNotification.operationType = elem.operationType
            tempNotification.taskModelType = elem.taskModelCode

            tempNotification.rightContent.gmtCreate = tempTime
            tempNotification.titleContent = elem.titleContent
            tempNotification.leftContent.selectLabel = elem.leftSelectTitle

            tempNotification.leftContent.msg = await this.handlePlaceholders(
              this.$props,
              elem.leftMsg
            )
            tempNotification.viewUrlParams = elem.viewUrlParams
            tempNotification.disposeUrlParams = elem.disposeUrlParams

            // 对参数模板进行替换
            tempNotification.viewUrlParams = this.deassignParams(
              this.params,
              tempNotification.viewUrlParams
            )
            tempNotification.disposeUrlParams = this.deassignParams(
              this.params,
              tempNotification.disposeUrlParams
            )
            if (index === 0) {
              tempNotification.isSelected = true
            }
            index++
            console.log(tempNotification)
            this.state.allNotifications.push(tempNotification)
          }
        }
      } else {
        this.$message.error(retInfo)
      }
    },
    // 查询cp关联的父cp与其id
    async todoGetProcess() {
      if (!this.params.cp) {
        return
      }
      const { success, retInfo, data } = await todo_get_process_post({
        cp: this.params.cp
      })
      if (success) {
        this.state.cpInfo.fatherCp = data.cp
        this.state.cpInfo.fatherCpId = data.id
      } else {
        this.$message.error(retInfo)
      }
    },
    // 拼接地址
    handleDisposalUrl(elem) {
      const tempParams = this.disposalUrlParams
      tempParams.id = this.state.cpInfo.fatherCpId
      if (this.cp === this.state.cpInfo.fatherCp) {
        tempParams.cp = this.params.cp
        tempParams.skipCp = this.params.cp
      } else {
        tempParams.cp = this.state.cpInfo.fatherCp
        tempParams.skipCp = this.params.cp
      }
      const jsonStr = JSON.stringify(tempParams).replace(/\\/g, '\\\\')
      elem.disposalUrlJsonStr = jsonStr
    },
    // 拼接地址
    // todo 根据不同业务拼接需要接口查询得到的地址参数
    handleViewlUrl(elem) {
      const jsonStr = JSON.stringify(elem.viewUrlParams).replace(/\\/g, '\\\\')
      elem.viewUrlJsonStr = jsonStr
    },
    clickCancel() {
      this.state.visiable = false
      this.$emit('closeTodoModal')
    },
    searchUser(val, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(val.toLowerCase()) >= 0
      )
    },
    // 调整修改人时触发
    changeSelectedUser(index, val) {
      if (val) {
        this.state.allNotifications[index].leftContent.selectedUserId = val
        // 待优化
        for (const user of this.state.allNotifications[index].leftContent
          .notifyUserArr) {
          if (user.userId === val) {
            this.state.allNotifications[index].rightContent.assignedPersonName =
              user.fullName
          }
        }
      } else {
        this.state.allNotifications[index].leftContent.selectedUserId = null
        this.state.allNotifications[index].rightContent.assignedPersonName =
          null
      }
    },
    formattedDateTime() {
      const nowDatetime = new Date()
      const year = nowDatetime.getFullYear()
      const month = String(nowDatetime.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要加1
      const day = String(nowDatetime.getDate()).padStart(2, '0')
      const hours = String(nowDatetime.getHours()).padStart(2, '0')
      const minutes = String(nowDatetime.getMinutes()).padStart(2, '0')
      const seconds = String(nowDatetime.getSeconds()).padStart(2, '0')
      return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
    },
    // 发起待办
    async todoInitiation(initaionParams) {
      const { success, retInfo, data } =
        await todo_initiation_post(initaionParams)
      if (success) {
        this.$message.success(data)
      } else {
        this.$message.error(retInfo)
      }
    },
    // 获取左上通知人select
    async todoGetConfigUser() {
      const params = {}
      if (this.businessType === 2) {
        params.businessModelCode = this.businessModelCode
        params.userDuty = 'valuer'
      }
      const { success, retInfo, data } = await todo_get_config_user_post(params)
      if (success) {
        for (const elem of this.state.allNotifications) {
          elem.leftContent.notifyUserArr = data
          if (this.businessType === 2) {
            elem.leftContent.selectedUserId = data[0].userId
            elem.rightContent.assignedPersonName = data[0].fullName
            break
          }
        }
        for (const notification of this.state.allNotifications) {
          if (notification.userDuty === 'craftsman') {
            notification.leftContent.selectedUserId = this.state.craftsmanId
            notification.rightContent.assignedPersonName =
              this.state.craftsmanName
          }
          if (notification.userDuty === 'platemaker') {
            notification.leftContent.selectedUserId = this.state.platemakerId
            notification.rightContent.assignedPersonName =
              this.state.platemakerName
          }
          if (notification.userDuty === 'designer') {
            notification.leftContent.selectedUserId = this.state.designerId
            notification.rightContent.assignedPersonName =
              this.state.designerName
          }
        }
        this.state.selectLoading = false
      } else {
        console.log(retInfo)
      }
    },
    async initMethods() {
      if (!this.businessModelCode) {
        return
      }
      // 查询默认信息
      this.state.visiable = true
      await this.todoGetProcess()
      await this.todoGetPageConfig()

      // 查询select框人员列表
      await this.todoGetConfigUser()
      // 查询cp关联人员信息
      if (this.params.cp) {
        await this.cpCardquery()
      }
    }
  }
}
</script>

<style scoped lang="less">
.modal-title {
  padding: 16px 24px;
  text-align: center;
  .title-icon {
    width: 60px;
    height: 60px;
  }
  .title-txt {
    margin-top: 10px;
    font-weight: bolder;
    font-size: 20px;
  }
  .title-remark {
    margin-top: 10px;
    color: #f69a65;
    font-size: 15px;
    font-weight: bold;
  }
}

.modal-main {
  max-height: 600px;
  overflow-x: hidden;
  overflow-y: auto;
  position: relative;
  .bottom {
    margin-bottom: 1vh;
  }
  .selectedContent {
    border: 1px solid #63a2e4;
  }
  .unSelectedContent {
    border: 1px solid #e8e8e8;
  }
  .content-title {
    font-weight: bolder;
    font-size: 18px;
  }
  .form-label {
    font-size: 16px;
    font-weight: bolder;
    margin-bottom: 5px;
  }
  .modal-content {
    position: relative;
    background: #fbfcfe;
    display: flex;
    height: 300px;
    padding: 20px;
    .modal-notication-text {
      text-align: center;
      padding-bottom: 20px;
      font-size: 18px;
      font-weight: bolder;
    }
    .modal-top-left-btn {
      position: absolute;
      top: 0;
      left: 0;
      width: 50px;
      height: 25px;
      background-color: #ccc;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      transition: background-color 0.3s;
      border-radius: 3px;
      color: #a7a7a7;
      &.selected {
        background-color: #63a2e4;
        color: white;
      }
    }
    .modal-content-left {
      padding: 0 24px;
      width: 50%;
      height: 100%;
      border-right: 1px solid #e8e8e8;
    }
    .modal-content-right {
      padding: 0 24px;
      width: 50%;
      height: 100%;
      // 预览相关css
      .chat-name {
        font-size: 12px;
        color: #b0abab;
        padding-left: 10px;
      }
      .chart-msg-after /deep/ span {
        color: #1989fa;
      }
      .chart-msg-before /deep/ span {
        color: #1989fa;
      }
      .chart-msg-before /deep/ img {
        width: 120px;
      }
      .chart-msg-before:before {
        border-style: solid;
        border-width: 6px;
        border-color: transparent #e6edf7 transparent transparent;
        width: 0px;
        top: 6px;
        height: 0px;
        content: '';
        position: absolute;
        left: 0;
        transform: translateX(-100%);
      }
      p {
        margin-bottom: 4px;
        padding-right: 4px;
      }
      img {
        width: 40px;
        height: 40px;
        border-radius: 3px;
      }
      ul {
        margin-bottom: 0;
        height: 100px;
        width: 46%;
      }
      .break-word {
        word-break: break-all;
        background: #e6edf7;
        border-radius: 4px;
        margin-left: 5px;
        position: relative;
        width: fit-content;
      }
    }
  }
}

/deep/.ant-form-item-label label {
  font-size: 20px;
  font-weight: bolder;
}
/deep/.ant-modal-body {
  padding: 0;
}
/deep/.a-modal {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  max-height: 80vh;
}
</style>
